package edu.chl.food_store.utility;

import java.text.MessageFormat;
import java.util.regex.*;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.*;

/**
 * EmailValidator:
 * Checks a given e-mail.
 * The email should contain a @ and end with .com/.se or similar.
 */
@FacesValidator(value = "emailValidator")
public class EmailValidator implements Validator {

    private Pattern pattern;
    private Matcher matcher;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String componentValue = value.toString();
        String message = null;
        if ("".equals(componentValue)) {
            message = "E-mail address is required.";
        } else {
            pattern = Pattern.compile(".+@.+\\.[a-z]+");
            matcher = pattern.matcher(componentValue);
            if (!matcher.find()) {
                message = MessageFormat.format("{0} is not a valid e-mail address.", componentValue);
            }
        }
        if (message != null) {
            FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message);
            throw new ValidatorException(facesMessage);
        }
    }
}
